package com.fadadianqi.mall.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.Constants;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.goods.model.Brand;
import com.fadadianqi.goods.service.GoodsService;
import com.fadadianqi.mall.model.Nav;
import com.fadadianqi.mall.product.model.AttrName;
import com.fadadianqi.mall.product.model.AttrRelation;
import com.fadadianqi.mall.product.model.AttrVal;
import com.fadadianqi.mall.product.model.ItemSPU;
import com.fadadianqi.mall.product.service.AttrService;
import com.fadadianqi.mall.product.service.ItemSPUService;
import com.fadadianqi.mall.service.NavService;
import com.yeqiangwei.commons.util.BeanUtils;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.ParamUtils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by aroot on 2/9/14.
 */
@Controller
public class ItemSPUController {


    @Autowired
    private AttrService attrService;
    @Autowired
    private NavService navService;
    @Autowired
    private ItemSPUService itemSPUService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private MessageSource messageSource;

    private List<Brand> getBrandsOrderByInitial(String initial) {
        return goodsService.findBrandByFirstLetter(initial, new Pagination(1, Integer.MAX_VALUE));
    }

    private List<Brand> getBrands(String q) {
        // TODO 品牌增加后得提供查询功能
        return null;
    }

    @RequestMapping(value = "/mall/item/brand/options")
    public String showBrandOptions(HttpServletRequest request, ModelMap modelMap) {
        List<Brand> brandList = null;
        String q = ParamUtils.getString(request, "q", null);
        if (ValidatorHelper.isEmpty(q)) {
            brandList = goodsService.findAllBrand();
        } else if (q.length() == 1) {
            brandList = getBrandsOrderByInitial(q);
        } else {
            // search brands
            brandList = getBrands(q);
        }
        modelMap.put("brandList", brandList);
        modelMap.put("q", q);
        modelMap.put("alphabet", Constants.ALPHABET);
        return "/mall/admin/item/brandOptions";
    }

    @RequestMapping(value = "/mall/ajax/adm/brand/list")
    public ResponseEntity<String> ajaxGetBrandList(HttpServletRequest request, ModelMap modelMap) {
        String errMsg = null;
        Boolean succeed = Boolean.FALSE;
        List<Brand> brandList = null;
        String q = ParamUtils.getString(request, "q", null);
        if (null == q) {
            brandList = goodsService.findAllBrand();
        } else if (q.length() == 1) {
            brandList = getBrandsOrderByInitial(q);
        } else {
            // search brands
            brandList = getBrands(q);
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(brandList, succeed, errMsg);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/mall/ajax/item/nav/attrs")
    public String ajaxAttrs(HttpServletRequest request, ModelMap modelMap) {
        String navId = ParamUtils.getString(request, "navId", null);
        List<AttrRelation> list = attrService.findNavAttrByNavId(navId);
        List<AttrRelationVO> voList = new ArrayList<AttrRelationVO>();
        if (ValidatorHelper.isNotEmpty(list)) {
            for (AttrRelation na : list) {
                AttrRelationVO vo = new AttrRelationVO();
                BeanUtils.copyProperties(vo, na);
                vo.setAttrName(attrService.getAttrNameById(na.getAttrNameId()));
                List<AttrVal> vals = attrService.findAttrValByAttrNameId(na.getAttrNameId());
                vo.setAttrVals(vals);
                voList.add(vo);
            }
        }
        modelMap.put("navAttrList", voList);
        return "/mall/admin/item/navAttrList";
    }

    @RequestMapping(value = "/mall/item/nav/options")
    public String showNavOptions(HttpServletRequest request, ModelMap modelMap) {
        List<Nav> navList = navService.showTreeList();
        modelMap.put("navList", navList);
        return "/mall/admin/item/navOptions";
    }

    @RequestMapping(value = {"/mall/adm/item/spu/form", "/mall/adm/product/item/create", "/mall/adm/product/item/edit"})
    public String showForm(HttpServletRequest request, ModelMap modelMap) {
        String id = ParamUtils.getString(request, "id", null);
        ItemSPU spu = itemSPUService.getById(id);
        modelMap.put("spu", spu);
        if (null != spu) {
            modelMap.put("brand", goodsService.getBrandById(spu.getBrandId()));
            List<Nav> navList = navService.findBySpuId(spu.getId());
            if (ValidatorHelper.isNotEmpty(navList)) {
                modelMap.put("currentNav", navList.get(navList.size() - 1));
            }
            List<AttrVal> attrValList = attrService.findAttrValBySpuId(spu.getId());
            modelMap.put("attrValList", attrValList);
        }
        return "/mall/admin/item/spuForm";
    }

    @RequestMapping(value = "/mall/ajax/adm/item/spu/save")
    public ResponseEntity<String> ajaxSave(HttpServletRequest request, ModelMap modelMap) {

        String id = ParamUtils.getString(request, "id", null);
        String navId = ParamUtils.getString(request, "navId", null);
        String brandId = ParamUtils.getString(request, "brandId", null);
        String name = ParamUtils.getString(request, "name", null);
        String displayName = ParamUtils.getString(request, "displayName", null);
        String details = ParamUtils.getString(request, "details", null);
        String[] vals = ParamUtils.getParameterValues(request, "vals");

        ItemSPUService.SPUForm spu = new ItemSPUService.SPUForm();
        spu.setId(id);
        spu.setAddTime(new Date());
        spu.setAttrValsId(JSONProvider.toJSON(vals));
        spu.setBrandId(brandId);
        spu.setDetails(details);
        spu.setDisplayName(displayName);
        spu.setName(name);
        spu.setUpdateTime(spu.getAddTime());
        spu.setCurrentNavId(navId);
        Boolean succeed = Boolean.FALSE;
        String errMsg = null;
        try {
            itemSPUService.save(spu);
            succeed = Boolean.TRUE;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                errMsg = messageSource.getMessage(e.getMessage(), null, Locale.getDefault());
            } catch (NoSuchMessageException e1) {
                e1.printStackTrace();
                errMsg = messageSource.getMessage("exception.mall.unknown", null, Locale.getDefault());
            }
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(spu, succeed, errMsg);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/mall/adm/product/items")
    public String showList(HttpServletRequest request, ModelMap modelMap) {
        List<ItemVO> items = new ArrayList<ItemVO>();
        Pagination pagination = new Pagination(request, 30);
        List<ItemSPU> spuList = itemSPUService.findAll(pagination);
        if (ValidatorHelper.isNotEmpty(spuList)) {
            for (ItemSPU spu : spuList) {
                ItemVO vo = new ItemVO();
                BeanUtils.copyProperties(vo, spu);
                vo.setBrand(goodsService.getBrandById(spu.getBrandId()));
                //List<Nav> navList = navService.findBySpuId(vo.getId());
                vo.setNavList(navService.findBySpuId(vo.getId()));
                vo.setAttrValList(attrService.findAttrValBySpuId(spu.getId()));
                items.add(vo);
            }
        }
        modelMap.put("items", items);
        return "/mall/admin/item/items";
    }

    public class AttrRelationVO extends AttrRelation {

        private AttrName attrName;
        private List<AttrVal> attrVals;

        public AttrName getAttrName() {
            return attrName;
        }

        public void setAttrName(AttrName attrName) {
            this.attrName = attrName;
        }

        public List<AttrVal> getAttrVals() {
            return attrVals;
        }

        public void setAttrVals(List<AttrVal> attrVals) {
            this.attrVals = attrVals;
        }
    }

    public static class ItemVO extends ItemSPU {

        private List<AttrVal> attrValList;

        private List<Nav> navList;

        private Brand brand;

        public List<AttrVal> getAttrValList() {
            return attrValList;
        }

        public void setAttrValList(List<AttrVal> attrValList) {
            this.attrValList = attrValList;
        }

        public List<Nav> getNavList() {
            return navList;
        }

        public void setNavList(List<Nav> navList) {
            this.navList = navList;
        }

        public Brand getBrand() {
            return brand;
        }

        public void setBrand(Brand brand) {
            this.brand = brand;
        }
    }
}
